package com.atguigu.tingshu.common.minio.config;

import com.atguigu.tingshu.common.minio.service.FileUploadService;
import com.atguigu.tingshu.common.minio.service.impl.FileUploadServiceImpl;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * ClassName: MinioAutoConfiguration
 * Package: com.atguigu.tingshu.common.minio.config
 * Description:
 *
 * @Author 梅超凡
 * @Create 2025/1/14 19:14
 * @Version 1.0
 */
//@Configuration
@EnableConfigurationProperties(MinioProperties.class)
@ConditionalOnProperty(
        prefix = "minio",//"minio" 为前缀的属性
        havingValue = "true",//havingValue为true时才加载
        value = "enable")//value为enable表示启用开关
public class MinioAutoConfiguration {
    // 日志

    @Bean
    public MinioClient minioClient(MinioProperties properties) {
//        MinioClient minioClient = MinioClient
//                .builder()
//                // 设置MinIO服务端地址
//                .endpoint(properties.getEndpointUrl())
//                // 设置访问凭证
//                .credentials(properties.getAccessKey(),
//                        properties.getSecreKey())
//                .build();
//        boolean found = false;
//        try {
//            // 判断bucket是否存在
//            found = minioClient.bucketExists(
//                    BucketExistsArgs
//                            .builder()
//                            .bucket(properties.getBucketName()).build());
//            if (!found) {
//                logger.info("Bucket不存在，创建bucket：{}", properties.getBucketName());
//                minioClient.makeBucket(
//                        MakeBucketArgs
//                                .builder()
//                                .bucket(properties.getBucketName()).build());
//                logger.info("bucket:{}创建成功", properties.getBucketName());
//            }
//            return minioClient;
//        } catch (Exception e) {
//            logger.error("MinIO初始化失败:{}", e.getMessage());
//            throw new RuntimeException("MinIO初始化失败，原因：", e);
//        }
        return MinioClient
                .builder()
                // 设置MinIO服务端地址
                .endpoint(properties.getEndpointUrl())
                // 设置访问凭证
                .credentials(properties.getAccessKey(),
                        properties.getSecreKey())
                .build();
    }

    @Bean
    public FileUploadService fileOpsService() {
        return new FileUploadServiceImpl();
    }
}
